﻿namespace Atomic.Plugins.Users.Data
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.SqlClient;

    using Atomic.Extensions;
    using Atomic.Collections;
    using Atomic.Data.AdoNet;
    using Atomic.Modules.Security;
    using Atomic.Plugins.Users.Models;

    /// <summary>
    /// 用户管理数据访问器。
    /// </summary>
    public class UserAdminRepository : RepositoryBase, IUserAdminRepository
    {
        /// <summary>
        /// 表名。
        /// </summary>
        private const string TABLE_NAME = "atomic_u_users";

        /// <summary>
        /// 表主键。
        /// </summary>
        private const string TABLE_KEY = "Id";

        /// <summary>
        /// 权限提供程序。
        /// </summary>
        private readonly IPermissionProvider _permissionProvider = null;

        /// <summary>
        /// 初始化用户管理数据访问器。
        /// </summary>
        /// <param name="permissionProvider">权限提供程序。</param>
        public UserAdminRepository(IPermissionProvider permissionProvider)
        {
            this._permissionProvider = permissionProvider;
        }

        /// <summary>
        /// 获得用户信息分页列表。
        /// </summary>
        /// <param name="pageIndex">页码。</param>
        /// <param name="pageSize">页大小。</param>
        /// <returns>用户信息分页列表。</returns>
        public IPageOfItems<ViewUser> GetUsers(int pageIndex, int pageSize)
        {
            string sqlWhere = string.Empty;

            var items = this.DataProvider.GetPage<ViewUser>(
                pageIndex, 
                pageSize, 
                TABLE_NAME, 
                TABLE_KEY,
                "Id, AccountNumber, Name, Email, Disable",
                sqlWhere, 
                "DESC", 
                0,
                this.GetUser);

            return new PageOfItems<ViewUser>(items, pageIndex, pageSize, this.DataProvider.GetCount(TABLE_NAME, sqlWhere));
        }

        /// <summary>
        /// 读取用户信息。
        /// </summary>
        /// <param name="dataReader">数据读取器。</param>
        /// <returns>用户信息。</returns>
        private ViewUser GetUser(IDataReader dataReader)
        {
            ViewUser user = new ViewUser();

            user.Id = dataReader.GetInt32(0);
            user.AccountNumber = dataReader.GetString(1);
            user.Name = dataReader.GetString(2);
            user.Email = dataReader.GetString(3);
            user.Disable = dataReader.GetInt32(4) == 0;

            return user;
        }
    }
}